package cn.yeyiu.videoplayer;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import cn.yeyiu.util.AndroidUtil;
import cn.yeyiu.util.NetUtil;
import cn.yeyiu.util.OrientationUtil;
import cn.yeyiu.util.ThreadUtil;
import cn.yeyiu.util.bean.VideoInfo;

public class VideoPlayerActivity extends AppCompatActivity {

    // videoView
    private YeyiuVideoPlayer yeyiuVideoPlayer;
    private FrameLayout helper;
    private IControlView simpleHelpView;
    private IControlView fullHelpView;
    private IControlView curHelpView;

    // data
    private VideoInfo videoInfo;
    private boolean isPlaying = false;
    private long click_time = 0;
    private float scroll_dist = 0;
    private int auto_hide_time = 0;

    // 分辨不同事件
    private GestureDetector gestureDetector;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);

        dataInit();
        bindView();
        bindEvent();
        playerInit();
    }


    // ------------------------
    //      activity start
    // ------------------------
    void dataInit() {
        videoInfo = JSONObject.parseObject(getIntent().getStringExtra("video_info"), VideoInfo.class);
        gestureDetector = new GestureDetector(VideoPlayerActivity.this,
                new GestureDetector.SimpleOnGestureListener() { // 处理具体事件
                    @Override
                    public boolean onSingleTapConfirmed(MotionEvent e) {//单击 切换控制显示
                        toggleHelper();
                        return true;
                    }

                    @Override
                    public boolean onDoubleTap(MotionEvent e) {// 双击 播放暂停
                        togglePlayer();
                        return true;
                    }

                    @Override
                    public void onLongPress(MotionEvent e) { // 长按 全屏 退出全屏
                        if (curHelpView == simpleHelpView) {
                            fullScreen();
                        } else {
                            simpleScreen();
                        }
                    }

                    @Override
                    public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                            float distanceX, float distanceY) { // 滑动 快进/退

                        scroll_dist += distanceX;
                        yeyiuVideoPlayer.showTip();
                        yeyiuVideoPlayer.setTip(String.format(Locale.CHINA,
                                "%s%02ds", scroll_dist >= 0 ? "-" : "+", (int) Math.abs(scroll_dist / 20)
                        ));
                        showHelper();
                        return true;
                    }
                });
    }

    void bindView() {
        yeyiuVideoPlayer = findViewById(R.id.video_my_player);
        helper = findViewById(R.id.video_helper);

        View loading = LayoutInflater.from(this).inflate(R.layout.item_video_init_loading, null);
        helper.addView(loading);
    }

    void bindEvent() {
        yeyiuVideoPlayer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                gestureDetector.onTouchEvent(event);
                if (event.getAction() == MotionEvent.ACTION_UP && yeyiuVideoPlayer.isTipShowing()) {
                    if (Math.abs(scroll_dist) > 20) {
                        // ms
                        int targetMsc = yeyiuVideoPlayer.getCurrentPosition() - (int) (scroll_dist * 50);
                        if (targetMsc < 0) {
                            targetMsc = 0;
                        } else if (targetMsc > yeyiuVideoPlayer.getDuration()) {
                            targetMsc = yeyiuVideoPlayer.getDuration();
                        }
                        yeyiuVideoPlayer.seekTo(targetMsc);
                    }
                    yeyiuVideoPlayer.hideTip();
                    scroll_dist = 0;
                }
                v.performClick();
                return true;
            }
        });
    }

    void playerInit() {
        String src = videoInfo.videoSrc;
        // error video
        if (src == null) {
            AndroidUtil.toast("url无效！");
            finish();
            return;
        }

        yeyiuVideoPlayer.setMyPlayerListener(new YeyiuVideoPlayer.MyPlayerListener() {
            @Override
            public void onPrepared() { // 准备好时播放
                yeyiuVideoPlayer.changeSize(YeyiuVideoPlayer.SCALE_RATIO);
                playerStart();
                initHelperView();
            }

            @Override
            public void onError(int what, int extra) { // 播放异常
                AlertDialog.Builder builder = new AlertDialog.Builder(VideoPlayerActivity.this);
                String msg = "视频播放失败，错误码: [" + what + "," + extra + "]\n\n";
                switch (what) {
                    case 0:// 不支持
                        msg += "无效链接, 检查协议！\n\n" + src;
                        break;
                    case 1:// 链接无效
                        msg += "当前安卓不支持该链接，请更换系统\n\n" + src;
                        break;
                    case 100:
                        msg += "媒体服务异常退出";
                        break;
                    default:
                        msg += "未知错误\n\n" + src;

                }
                builder.setMessage(msg)
                        .setPositiveButton("复制链接", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                AndroidUtil.copy(VideoPlayerActivity.this, src);
                                finish();
                            }
                        })
                        .setNegativeButton("忽略", null)
                        .setCancelable(false);
                builder.show();
            }
        });

        // has header
        if (videoInfo.headers!=null){
            yeyiuVideoPlayer.setVideoPath(src, videoInfo.headers);
        }else{
            yeyiuVideoPlayer.setVideoPath(src);
        }
        // has info
        if (videoInfo.info != null) {
            AndroidUtil.toast(videoInfo.info);
        }
    }


    // ------------------------
    //      tool func
    // ------------------------
    private boolean helperLock = false;

    void showHelper() {
        auto_hide_time = 5000;
        showHelperView();
        if (!helperLock) {
            ThreadUtil.run(() -> {
                helperLock = true;
                while (auto_hide_time > 0) {
                    ThreadUtil.sleep(100);
                    auto_hide_time -= 100;
                }
                helperLock = false;
                hideHelperView();
            });
        }
    }

    void hideHelper() {
        hideHelperView();
        auto_hide_time = 0;
    }

    void toggleHelper() {
        if (auto_hide_time <= 0) {
            showHelper();
        } else {
            hideHelper();
        }
    }

    void showHelperView() {
        simpleHelpView.show();
        fullHelpView.show();
    }

    void hideHelperView() {
        simpleHelpView.hide();
        fullHelpView.hide();
    }

    // update global view
    void updateHelperViewBy(IControlView controlView) {
        // update helper view
        helper.removeAllViews();
        helper.addView(controlView.rootView);
        curHelpView = controlView;
        // recount show time
        showHelper();
    }

    // 控制器 布局
    IControlView getSimpleHelpView() {
        SimpleHelperView simpleHelpView = new SimpleHelperView(this);

        simpleHelpView.back.setOnClickListener((v) -> {
            finish();
        });
        // open browser
        simpleHelpView.share.setOnClickListener(v -> {
            AndroidUtil.openInBrowser(this, Uri.parse(this.videoInfo.videoSrc));
        });
        simpleHelpView.play.setOnClickListener(v -> {
            togglePlayer();
        });

        simpleHelpView.fullscreen.setOnClickListener(v -> {
            fullScreen();
        });

        ViewGroup.LayoutParams layoutParams = simpleHelpView.progress_cur.getLayoutParams();
        simpleHelpView.progress.setOnTouchListener((v, e) -> {
            long time = System.currentTimeMillis();
            if (time - click_time < 300) {
                return true;
            }
            click_time = time;

            // progress
            float x = e.getX();
            float cap = x / v.getWidth();
            layoutParams.width = (int) x;
            simpleHelpView.progress_cur.setLayoutParams(layoutParams);

            // time
            int currentTime = yeyiuVideoPlayer.getCurrentPosition() / 1000;
            String curTimeStr = String.format(Locale.CHINA, "%02d:%02d", currentTime / 60, currentTime % 60);
            simpleHelpView.time_cur.setText(curTimeStr);

            // player
            yeyiuVideoPlayer.seekTo((int) (cap * yeyiuVideoPlayer.getDuration()));

            v.performClick();
            return true;
        });

        simpleHelpView.title.setText(this.videoInfo.title);
        if (isPlaying) {
            simpleHelpView.start();
        } else {
            simpleHelpView.pause();
        }

        return simpleHelpView;
    }

    IControlView getFullHelpView() {
        FullHelperView fullHelpView = new FullHelperView(this);

        // event
        fullHelpView.back.setOnClickListener((v) -> {
            simpleScreen();
        });
        // open browser
        fullHelpView.share.setOnClickListener(v -> {
            AndroidUtil.openInBrowser(this, Uri.parse(this.videoInfo.videoSrc));
        });

        fullHelpView.play.setOnClickListener(v -> {
            togglePlayer();
        });

        fullHelpView.speed.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView speedView = (TextView) view;
                yeyiuVideoPlayer.setSpeed(Float.parseFloat(speedView.getText().toString()));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        fullHelpView.scale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                TextView scaleView = (TextView) view;
                switch (scaleView.getText().toString()){
                    case "比例全屏":
                        yeyiuVideoPlayer.changeSize(YeyiuVideoPlayer.SCALE_RATIO);
                        break;
                    case "拉伸全屏":
                        yeyiuVideoPlayer.changeSize(YeyiuVideoPlayer.SCALE_FULL);
                        break;
                    case "比例铺满":
                        yeyiuVideoPlayer.changeSize(YeyiuVideoPlayer.SCALE_RATIO_FULL);
                        break;
                    case "原分辨率":
                        yeyiuVideoPlayer.changeSize(YeyiuVideoPlayer.SCALE_RAW);
                        break;
                    default:break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        ViewGroup.LayoutParams layoutParams = fullHelpView.progress_cur.getLayoutParams();
        fullHelpView.progress.setOnTouchListener((v, e) -> {
            long time = System.currentTimeMillis();
            if (time - click_time < 300) {
                return true;
            }
            click_time = time;

            // progress
            float x = e.getX();
            float cap = x / v.getWidth();
            layoutParams.width = (int) x;
            fullHelpView.progress_cur.setLayoutParams(layoutParams);

            // time
            int currentTime = (int) (yeyiuVideoPlayer.getCurrentPosition() / 1000);
            String curTimeStr = String.format(Locale.CHINA, "%02d:%02d", currentTime / 60, currentTime % 60);
            fullHelpView.time_cur.setText(curTimeStr);

            // player
            yeyiuVideoPlayer.seekTo((int) (cap * yeyiuVideoPlayer.getDuration()));

            v.performClick();
            return true;
        });

        //
        fullHelpView.favour.setOnClickListener(v -> {
            AndroidUtil.saveLikes(this, videoInfo);
        });
        fullHelpView.download.setOnClickListener(v -> {
            NetUtil.downloadVideo(this, videoInfo);
        });

        fullHelpView.title.setText(videoInfo.title);

        // time
        fullHelpView.tool_time.setText(new Date().toString());
        // net
        ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conn == null) {
            fullHelpView.tool_net.setText("NoNet");
        } else {
            NetworkInfo netInfo = conn.getActiveNetworkInfo();
            fullHelpView.tool_net.setText(netInfo.getTypeName());
        }
        // battery
        BatteryManager batteryManager = (BatteryManager) getSystemService(Context.BATTERY_SERVICE);
        int capacity = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        fullHelpView.tool_battery.setText(String.valueOf(capacity));

        if (isPlaying) {
            fullHelpView.start();
        } else {
            fullHelpView.pause();
        }

        return fullHelpView;
    }

    void initHelperView() {
        simpleHelpView = getSimpleHelpView();
        fullHelpView = getFullHelpView();
        // 开始计时
        updateTimeAndProgress(simpleHelpView);
        updateTimeAndProgress(fullHelpView);
        // 优选
        updateHelperViewBy(simpleHelpView);
    }

    void playerStart() {
        isPlaying = true;
        yeyiuVideoPlayer.start();
        if (curHelpView != null) {
            curHelpView.start();
        }
    }

    void playerPause() {
        isPlaying = false;
        yeyiuVideoPlayer.pause();
        if (curHelpView != null) {
            curHelpView.pause();
        }
    }

    // switch player status
    void togglePlayer() {
        if (isPlaying) {
            playerPause();
        } else {
            playerStart();
        }
    }

    // fullscreen and update layout
    void fullScreen() {
        // 更换布局
        updateHelperViewBy(fullHelpView);
        // 根据视频比例选择横竖屏
        OrientationUtil.sensorDisplayOrientation(this, yeyiuVideoPlayer.isVideoHorizontal());
    }

    void simpleScreen() {
        updateHelperViewBy(simpleHelpView);
        OrientationUtil.cancelDisplayRotation(this);
    }

    // 计时 and 更新进度
    void updateTimeAndProgress(IControlView helper) {
        // 获取最大秒数
        int duration = yeyiuVideoPlayer.getDuration() / 1000;
        // 设置最大时间
        helper.time_max.setText(String.format(Locale.CHINA, "%02d:%02d", duration / 60, duration % 60));
        // 更新
        ThreadUtil.run(() -> {
            // 获取当前进度条
            ViewGroup.LayoutParams layoutParams = helper.progress_cur.getLayoutParams();
            while (!this.isFinishing()) {
                if (isPlaying) {
                    // 当前秒
                    int currentTime = yeyiuVideoPlayer.getCurrentPosition() / 1000;
                    // 时间字符
                    String curTimeStr = String.format(Locale.CHINA, "%02d:%02d", currentTime / 60, currentTime % 60);
                    // 进度条长度
                    layoutParams.width = (int) (currentTime / (float) duration * helper.progress.getWidth());
                    // 更新 进度条和时间ui
                    helper.progress_cur.post(() -> {
                        helper.time_cur.setText(curTimeStr);
                        helper.progress_cur.setLayoutParams(layoutParams);
                    });
                }
                ThreadUtil.sleep(500);
            }
        });
    }

    // ----------------------------
    //       Overrider
    // ----------------------------

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        yeyiuVideoPlayer.postDelayed(() -> {
            yeyiuVideoPlayer.changeSize(YeyiuVideoPlayer.SCALE_RATIO);
        }, 100);
    }

    @Override
    protected void onResume() {
        yeyiuVideoPlayer.resume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        yeyiuVideoPlayer.pause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        yeyiuVideoPlayer.release();
        super.onDestroy();
    }

}